import * as API from "@/services";
import React, {useCallback, useContext, useMemo, useState} from "react";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {correspVal} from "@/utils/biz";
import {message} from "antd";
import queryString from "query-string";
import {getAuthToken} from "@/utils/auth";
import useAuthedCheck from "@/components/hooks/UseAuthedCheck";
import {processError, triggerDownload} from "@/utils/download";
import {Hash} from "history";
import HxIcon from "@/components/HxIcon";
import {LoadingOutlined} from "@ant-design/icons";


interface JournalArticleHelpResult {
  /** 文章引文 **/
  articleQuote: string;
  /** 分享链接 **/
  shareUrl: string;
  /** doi链接 **/
  doiUrl: string;
  /** 是否正在 下载 中 **/
  downloading: boolean;
  /** 下载文章pdf**/
  downloadArticlePdf: (redirectHash?: Hash) => void;
  downloadArticlePdfIcon: React.ReactNode;
  /** 收藏/取消收藏 文章 **/
  favArticle: (onSuccess?: (record: API.FrontArticle) => void, redirectHash?: Hash) => void;
  favIcon: React.ReactNode;
  /** 是否正在 收藏/取消收藏 中 **/
  favoriting: boolean;
}


const useJournalArticleHelp = (article?: API.FrontArticle): JournalArticleHelpResult => {
  const {isZhCN} = useContext(HxConfigContext);
  const authedCheck = useAuthedCheck();
  const [downloading, setDownloading] = useState(false);
  const [favoriting, setFavoriting] = useState(false);

  const articleQuote = useMemo(() => {
    const quoteArr = [
      correspVal(isZhCN, article?.articleAuthorCn, article?.articleAuthorEn),
      correspVal(isZhCN, article?.articleTitleCn, article?.articleTitleEn),
      `${correspVal(isZhCN, article?.journal?.journalNameCn || article?.journalNameCn, article?.journal?.journalNameEn || article?.journalNameEn)},
      ${article?.period?.year || article?.articleYear}, ${article?.period?.volume || article?.articleVolume}(${article?.period?.period || article?.articlePeriod}): ${article?.articleStartpage}-${article?.articleEndpage}`,
      `doi: ${article?.articleDoi}`
    ]
    return quoteArr.join(". ")
  }, [isZhCN, article]);

  const shareUrl = useMemo(() => {
    const detailPath = `/journal/${article?.journal?.id || article?.journalId}/article/${article?.id}`;
    const url = `${window.location.origin}${detailPath}`;
    return url;
  }, [article]);

  const doiUrl = useMemo(() => {
    return `https://doi.org/${article?.articleDoi}`;
  }, [article]);


  const downloadArticlePdf = useCallback(async (redirectHash?: Hash) => {
    authedCheck(async () => {
      if (downloading) {
        return;
      }
      try {
        if (!article) {
          return;
        }
        setDownloading(true);
        const resp = await API.preCheckArticleDownload(article.id, {skipErrorHandler: true});
        if (resp.flag) {
          const fname = `${article?.articleDoi}.pdf`
          const searchString = queryString.stringify({
            authToken: getAuthToken(),
            fname
          })
          const url = `${REQUEST_BASE_URL}/api/v1/front/article/${article?.id}/pdf?${searchString}`;
          triggerDownload(url)
        }
      } catch (e: any) {
        processError(e, isZhCN);
      } finally {
        setDownloading(false);
      }
    }, redirectHash)
  }, [isZhCN, article]);

  const favArticle = useCallback(async (onSuccess?: (record: API.FrontArticle) => void, redirectHash?: Hash) => {
    authedCheck(async () => {
      if (favoriting) {
        return;
      }
      try {
        if (!article) {
          return;
        }
        setFavoriting(true);
        const resp = await API.fav("article", article!.id, !!article?.hascollection);
        if (resp.flag) {
          message.success(!article?.hascollection ? "收藏成功" : "已取消收藏");
          onSuccess?.({
            ...article!,
            hascollection: !article?.hascollection,
          });
        }
      } finally {
        setFavoriting(false);
      }
    }, redirectHash)
  }, [article]);

  const favIcon = useMemo(() => {
    if (favoriting) {
      return <LoadingOutlined/>;
    }
    return !!article?.hascollection ? <HxIcon type="hxicon-shoucang-yishoucang"/> : <HxIcon type="hxicon-shoucang"/>;
  }, [downloading, article]);

  const downloadArticlePdfIcon = useMemo(() => {
    if (downloading) {
      return <LoadingOutlined/>;
    }
    return <HxIcon type={"hxicon-xiazai"}/>;
  }, [downloading, article]);

  return {
    articleQuote,
    shareUrl,
    doiUrl,
    downloading,
    downloadArticlePdf,
    favArticle,
    favIcon,
    favoriting,
    downloadArticlePdfIcon,
  }
}

export default useJournalArticleHelp;
